<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // "2023/09/21 11:57:56"
    // "2023/09/21 11:57"
    // "2023/09/21"
    // "11:57:56"
    // "09/21"

    // 根据传入的日期,输出指定格式的时间

    /*  var pattern = "YYYY-MM-DD hh:mm:ss"; // 期望输出格式
     var pattern = "YYYY-MM-DD"; // 期望输出格式
     var pattern = "hh:mm:ss"; // 期望输出格式
     
     var date = new Date();
 
     var year = date.getFullYear();
     var month = date.getMonth() + 1;
     var day = date.getDate();
 
     var hour = date.getHours();
     var min = date.getMinutes();
     var sec = date.getSeconds();
 
     var result = pattern.replace("YYYY",year).replace("MM",month).replace("DD",day).replace("hh",hour).replace("mm",min).replace("ss",sec);
 
     console.log(result); */


    function dateFormat(pattern, date) {
        // var pattern = "YYYY-MM-DD hh:mm:ss"; // 期望输出格式

        /* if(date == undefined){ // 没有第二参数
            date = new Date();  // 默认获取当前时间
        }else{
            // new Date("2023-10-1")
            // new Date(new Date("2023-10-1"))
            // new Date(1000000000)
            date = new Date(date); 
        } */

        date = date == undefined ? new Date() : new Date(date);

        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();

        var hour = date.getHours();
        var min = date.getMinutes();
        var sec = date.getSeconds();

        function beauty(num){
            return num < 10 ? "0" + num : num;
        }

        return pattern.replace("YYYY", year).replace("MM", beauty(month)).replace("DD", beauty(day)).replace("hh", beauty(hour)).replace("mm", beauty(min)).replace("ss", beauty(sec));
    }



    console.log(dateFormat("YYYY-MM-DD hh:mm:ss"));
    console.log(dateFormat("YYYY-MM-DD hh:mm"));
    console.log(dateFormat("YYYY-MM-DD"));
    console.log(dateFormat("hh:mm:ss"));
    
    console.log(dateFormat("YYYY-MM-DD","2023-7-19 16:53:57"));
    console.log(dateFormat("YYYY-MM-DD hh:mm","2023-7-19 16:53:57"));


</script>

</html>